<template>
  <!-- 预处理任务管理 -->
  <div class="model-manage">
    <div class="mm-panel-wrapper-left">
      <Tree ref="leftTreeRef" :isOwnAccount="true" :topAdd="true" :topAddMenu="right_menuList.rightMenuList_1"
        :folderMenu="right_menuList.rightMenuList_18" :secondMenu="right_menuList.rightMenuList_18_2"
        :fileMenu="right_menuList.rightMenuList_18_3" :treeData="ownTreeData" :currentNodeKey="currentNodeKey"
        :defaultExpandedKeys="defaultExpandedKeys" @handleAddNode="handleAddModel"
        @addOrUpdateFolder="handleAddOrUpdateFolder" @nodeClick="nodeClick" @nodeDelete="handleNodeDelete"
        @moveNodeOrder="moveNodeOrder" @handleMenuClick="handleMenuClick">
      </Tree>
    </div>
    <div class="mm-divider"></div>
    <div class="mm-panel-wrapper-right">
      <div class="padding20">
        <!-- 任务 -->
        <div style="height: 100%;" v-if="isFlow && !isFolder">
          <div class="mm-panel-title mb-10">
            预处理任务基础信息
            <el-button style="float: right;" class="ml-10" type="primary" @click="handleSave">保存</el-button>
          </div>
          <el-form ref="itemForm" :model="itemForm" :rules="rules" label-width="150px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="名称" prop="name">
                  <el-input v-model="itemForm.name"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="创建日期" prop="createTime">
                  <el-date-picker v-model="itemForm.createTime" type="date" placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="描述" prop="description">
              <el-input type="textarea" v-model="itemForm.description"></el-input>
            </el-form-item>
          </el-form>
          <div class="mm-panel-title mb-10">
            任务流设置
            <el-button style="float: right;" class="ml-10" type="primary" @click="openRunSet">运行</el-button>
          </div>
          <div style="border: 1px solid var(--ui-border-color-split);padding: 20px;height: calc(100% - 180px);">
            <Workflow ref="workflowRef" v-if="loadWorkflow" :treeData="buildTree" :initData="itemForm.taskFlowData" />
          </div>
        </div>
        <!-- 实例 -->
        <div style="height: 100%;" v-else-if="!isFolder">
          <div class="mm-panel-title mb-10">
            运行状态
            <el-button style="float: right;" class="ml-10" type="primary" @click="handleClose">停止</el-button>
          </div>
          <el-form ref="instForm" :model="instForm" label-width="150px">
            <el-row>
              <el-col :span="24">
                <el-form-item label="名称" prop="name">
                  <el-input v-model="instForm.name" :readonly="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="状态" prop="runStateName">
                  <el-input v-model="instForm.runStateName" :readonly="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="开始时间" prop="createTime">
                  <el-date-picker v-model="instForm.startTime" type="datetime" placeholder="选择日期" :readonly="true">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="进度" prop="name">
                  <el-input v-model="instForm.progresPct" :readonly="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="结束时间" prop="createTime">
                  <el-date-picker v-model="instForm.finishTime" type="datetime" placeholder="选择日期" :readonly="true">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div class="flex" style="height: calc(100% - 160px);">
            <div style="width: 50%;padding: 0 20px 0 0;height: 100%;">
              <div class="mm-panel-title mb-10">
                任务流状态
              </div>
              <div
                style="height: calc(100% - 40px); border: 1px solid var(--ui-border-color-split);overflow: hidden;border-radius: 10px;">
                <Workflow ref="workInstRef" v-if="loadWorkInst" :treeData="[]" :initData="instForm.taskFlowData" />
              </div>
            </div>
            <div style="width: 50%;padding: 0 0 0 20px;height: 100%;">
              <div class="mm-panel-title mb-10">
                运行结果信息
              </div>
              <div class="json-display-container">
                <el-scrollbar style="height: 100%;">
                  <pre class="json-pre"><code>{{ formattedWorkflowData }}</code></pre>
                </el-scrollbar>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog title="新增" :visible.sync="openDialog" width="800px" append-to-body>
      <div></div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary">确 定</el-button>
        <el-button @click="openDialog = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="参数设置" :visible.sync="runSet" width="800px" append-to-body>
      <div v-if="runSet" style="height: 550px;">
        <Workflow ref="runSetRef" v-if="runSet" :treeData="[]" :initData="itemForm.taskFlowData" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleOpen">确 定</el-button>
        <el-button @click="runSet = false">取 消</el-button>
      </div>
    </el-dialog>
    <AddOrUpdateFolder v-if="isAddOrUpdateFolder" :preSetType="3" ref="addOrUpdateFolderRef" @refresh="getList">
    </AddOrUpdateFolder>
    <AddOrUpdateModel v-if="isAddOrUpdateModel" :preSetType="3" ref="addOrUpdateModelRef" @refresh="getList">
    </AddOrUpdateModel>
  </div>
</template>

<script>
import { mapState } from "vuex";
import {
  getTreeApi,
  deleteTreeApi,
  getFlowmDetailsApi,
  startTaskFlow,
  closeFlowApi,
  updateFlowApi,
  getPreAlgOperatorBuildTree,
  getFlowInst
} from "@/api/myspace/preprocessing/index";
import Tree from "@/components/LeftTree/tree.vue";
import AddOrUpdateModel from "./components/add-or-update-model.vue";
import AddOrUpdateFolder from "./components/add-or-update-folder.vue";
import Workflow from "@/components/Workflow/index.vue";

export default {
  data() {
    return {
      isFlow: true,
      runSet: false,// 运行时设置参数用弹窗
      loadWorkflow: false,// 加载任务流组件
      loadWorkInst: false,// 加载任务流实例组件
      buildTree: {},// 设置任务流用的模型构建树
      rules: {
        name: [{ required: true, message: "名称不可为空", trigger: "blur" }],
      },
      itemForm: {
        name: "", //名称
        createTime: "",
        description: "", //描述
        taskFlowData: ""
      },
      instForm: {
        name: "",
        progresPct: '',
        startTime: "",
        finishTime: "",
        taskFlowData: "",
        workflowData: ""
      },
      openDialog: false,
      loading: false,
      tableList: [
        {
          name: "xxxxx",
          size: 300,
          count: 10000,
          description: "针对xxx生成的样本数据",
          qualityResult: "完整性80%，多样性60%",
          createTime: "2021-01-01 10:10:10",
        },
      ],
      queryParams: {
        // 查询参数
        pageNum: 1,
        pageSize: 10,
        name: "",
        modelId: "",
        folderId: "",
      },
      isAddOrUpdateModel: false, // 是否打开新增数据模型弹框
      isAddOrUpdateFolder: false, // 是否打开创建目录的弹框
      isFolder: false, // 是否展示文件夹详情
      isFile: false, // 是否展示文件详情
      isModel: false, //是否是模型详情
      isModelGroupDetail: false, // 是否展示模型组详情,
      selectedNodeInfo: {}, // 当前选中节点的信息
      ownTreeData: [], // 本账户模型列表
      currentNodeKey: 0, // 当前选中节点的key
      defaultExpandedKeys: [], // 默认展开的节点
    };
  },
  components: {
    Tree,
    AddOrUpdateModel,
    AddOrUpdateFolder,
    Workflow
  },
  computed: {
    ...mapState({
      right_menuList: (state) => state.modelManageTool.right_menuList,
      selectedNodeId: (state) => state.modelManageTool.model.selectedNodeId,
      expandedNodeIds: (state) => state.modelManageTool.model.expandedNodeIds,
    }),
    formattedWorkflowData() {
      try {
        if (!this.instForm.workflowData) {
          return '暂无运行结果数据';
        }

        if (typeof this.instForm.workflowData === 'string') {
          if (this.instForm.workflowData.trim() === '') {
            return '暂无运行结果数据';
          }
          const parsed = JSON.parse(this.instForm.workflowData);
          return JSON.stringify(parsed, null, 2);
        } else {
          return JSON.stringify(this.instForm.workflowData, null, 2);
        }
      } catch (e) {
        console.error('JSON解析错误:', e);
        return this.instForm.workflowData || '数据格式错误';
      }
    }
  },
  async created() {
    await this.getList();
    this.currentNodeKey = this.selectedNodeId;
    this.defaultExpandedKeys = this.expandedNodeIds;
    this.$nextTick(() => {
      this.$refs.leftTreeRef.$refs.treeRef.setCurrentKey(this.currentNodeKey);
    });
  },
  methods: {
    // 打开二次配置任务流窗口
    openRunSet() {
      this.runSet = true
    },
    // 开启
    handleOpen() {
      let rep = JSON.parse(JSON.stringify(this.itemForm))
      rep.taskFlowData = JSON.stringify(this.$refs.runSetRef.getData())
      startTaskFlow(rep).then((res) => {
        this.$message.success("开启成功");
        this.getList()
        this.runSet = false
      });
    },
    // 关闭
    handleClose() {
      closeFlowApi(this.instForm.id).then((res) => {
        this.$message.success("关闭成功");
        this.getDetail()
      });
    },
    getDetail() {

      getFlowmDetailsApi(this.itemForm.id || this.instForm.id).then((response) => {
        if (response.code == 200) {
          this.itemForm = response.data;
          this.instForm = {}
          this.$refs.itemForm.clearValidate();
        }
      })
    },
    // 保存
    // 保存
    handleSave() {
      if (!this.itemForm.id) {
        return
      }
      let rep = this.$refs.workflowRef.getData()
      this.itemForm.taskFlowData = JSON.stringify(rep)
      const repList = [...new Set(rep.nodes.map(node => node.data.id))];
      this.itemForm.refPreAlgorithmIds = repList.join(',');
      // 校验文件夹表单
      this.$refs.itemForm.validate((valid) => {
        if (valid) {
          updateFlowApi(this.itemForm).then((res) => {
            this.$message.success("保存成功");
            this.getDetail()
            // 重置校验状态
            this.$refs.itemForm.clearValidate();
          }).catch(() => {
            // 保存失败时也重置校验状态（可选）
            this.$refs.itemForm.clearValidate();
          });
        } else {
          this.$message.warning("请填写必填项");
          return false;
        }
      });
    },
    handleCommand(command) {
      switch (command) {
        case "进入":
          this.$router.push({ path: "/training-mission" });
          break;
        case "编辑":
          break;
        case "删除":
          break;
        default:
          break;
      }
    },
    //新增
    handleAdd() {
      this.openDialog = true;
    },
    //查询
    handleQuery() { },
    //重置搜索条件
    resetQuery() { },
    async getList(newNodeId) {
      await getTreeApi({ preSetType: 3 }).then((res) => {
        if (res.code == 200 && Array.isArray(res.data)) {
          this.ownTreeData = res.data.length > 0 ? res.data[0].commonTreeList : [];
          const targetId = newNodeId || this.selectedNodeId;
          const targetnode = targetId
            ? this.recurNodeForTarget(this.ownTreeData, targetId)
            : this.ownTreeData[0];
          this.nodeClick(targetnode);
        }
      });
    },
    // 递归获取当前树节点
    recurNodeForTarget(nodeArr, id) {
      for (let i = 0; i < nodeArr.length; i++) {
        if (nodeArr[i].id == id) {
          return nodeArr[i];
        } else {
          if (nodeArr[i].children && nodeArr[i].children.length > 0) {
            let node = this.recurNodeForTarget(nodeArr[i].children, id);
            if (node) {
              return node;
            }
          }
        }
      }
    },
    // 新增文件夹
    handleAddOrUpdateFolder(sign, node) {
      this.isAddOrUpdateFolder = true;
      this.$nextTick(() => {
        this.$refs["addOrUpdateFolderRef"].init(
          sign,
          node,
          this.ownTreeData,
          "account"
        );
      });
    },
    // 新增数据模型
    handleAddModel(node) {
      this.isAddOrUpdateModel = true;
      this.$nextTick(() => {
        this.$refs["addOrUpdateModelRef"].init(undefined, node);
      });
    },
    // 点击树节点，右侧展示详细信息
    async nodeClick(node) {
      this.loadWorkflow = false;
      this.loadWorkInst = false;
      if (node == undefined) {
        return;
      }
      this.selectedNodeInfo = node;
      this.currentNodeKey = node.id;
      this.$nextTick(() => {
        this.$refs.leftTreeRef.$refs.treeRef.setCurrentKey(this.currentNodeKey);
      });
      this.$store.commit("modelManageTool/SET_SELECTED_NODE_ID", {
        moduleName: "model",
        id: node.id,
      });
      if (!node.data) return;

      if (node.type == 0) {
        // 点击的文件夹
        this.isFolder = true;
        this.isModel = false;
        this.$store.commit("modelManageTool/SET_EXPANDED_NODE_IDS", {
          moduleName: "model",
          idList: Array.from(new Set([...this.defaultExpandedKeys, node.id])),
        });
      } else {
        // 点击的文件
        this.isFolder = false;
        this.isFile = true;
        this.isModel = true;
        // node.data.preSetType==3 任务 node.data.preSetType==4 任务流实例
        if (node.data.preSetType == 3) {
          this.isFlow = true;
          const res = await getFlowmDetailsApi(node.data.refId);
          if (res.code === 200) {
            this.itemForm = res.data
            this.instForm = {}
            this.$refs.itemForm.clearValidate();
          } else {
            this.$message.error(res.msg);
          }
          getPreAlgOperatorBuildTree().then(res => {
            this.buildTree = res.data.length > 0 ? res.data[0].commonTreeList : [];
            this.loadWorkflow = true;
          })
        } else {
          this.isFlow = false;
          getFlowInst(node.data.refId).then(res => {
            this.instForm = res.data
            this.itemForm = {}
            this.$refs.instForm.clearValidate();
            this.loadWorkInst = true;
          })
        }

      }
    },
    /**
         * 树节点删除事件的回调
         * @param node 被删除的节点
         */
    handleNodeDelete(node) {
      this.$confirm(
        `确定删除${node.type == 0 ? "目录" : "任务"}  ${node.data.name
        } ?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          customClass: "message-box-style",
          type: "warning",
        }
      )
        .then(async () => {
          const response = await deleteTreeApi(node.id, 3);
          if (response.code == 200) {
            this.$message.success(
              this.$toolHandle.getI18nName(
                this.$zh.setup.responseText,
                this.$en.setup.responseText,
                this.$i18n.locale,
                "success"
              )
            );
            if (node.id == this.currentNodeKey) {
              this.isFolder = false;
              this.isModel = false;
            }
            this.loadWorkflow = false;
            this.loadWorkInst = false;
            this.runSet = false;
            this.getList();
          }
        })
        .catch(() => { });
    },
    // 移动树节点的顺序
    moveNodeOrder(draggingNode, dropNode, dropType) {
      moveTreeNodeOrder({
        movedNodeId: draggingNode.data.id, // 被移动节点的id
        referenceNodeId: dropNode.data.id, // 参照节点的id
        position: dropType == "after" ? 1 : dropType == "before" ? -1 : 0, // 相对位置，before:-1,into:0,after:1
        ancestors: draggingNode.data.data.ancestors, // 祖先
        folderChildrenOrder: {
          parentId:
            dropType == "inner" ? dropNode.data.id : dropNode.data.parentId, // 父级id
          siblingIds:
            dropType == "inner"
              ? Array.from(dropNode.childNodes).map((item) => item.data.id)
              : Array.from(dropNode.parent.childNodes).map(
                (item) => item.data.id
              ),
        },
      }).then((response) => {
        if (response.code == 200) {
          this.$message.success(
            this.$toolHandle.getI18nName(
              this.$zh.setup.responseText,
              this.$en.setup.responseText,
              this.$i18n.locale,
              "success"
            )
          );
          this.getList();
        }
      });
    },
    // 点击菜单项触发的事件
    handleMenuClick(menu, node) {
      switch (menu.name) {
        case "新增任务":
          this.handleAddModel(node);
          break;
        case "新增分类":
          this.handleAddOrUpdateFolder("add");
          break;
        // case "新增任务":
        //   this.handleAddOrUpdateFolder("add", node);
        //   break;
        case "编辑":
          this.handleAddOrUpdateFolder("edit", node);
          break;
        case "复制":
          // 文件的复制
          this.handleCopyFile(node);
          break;
        case "删除":
          // 文件夹/文件的删除
          this.handleNodeDelete(node);
          break;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.model-manage {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;

  .mm-panel-wrapper-left {
    width: 300px;
    height: 100%;
    flex-grow: 0;
    flex-shrink: 0;
    display: flex;
    position: relative;
    padding: 0 10px;
  }

  .mm-divider {
    width: 1px;
    height: auto;
    flex-grow: 0;
    position: relative;
    align-self: stretch;
    background-color: var(--ui-border-color-split);
  }

  .mm-panel-wrapper-right {
    width: 256px;
    height: 100%;
    min-width: 0px;
    flex-grow: 1;
    flex-shrink: 1;
    display: flex;
    position: relative;
    overflow: auto;
  }
}

.padding20 {
  padding: 20px;
  width: 100%;
}

.json-display-container {
  height: calc(100% - 40px);
  overflow: hidden;
  border-radius: 10px;
  border: 1px solid var(--ui-border-color-split);
  background-color: #fafafa;
}

.json-pre {
  margin: 0;
  padding: 15px;
  background-color: #ffffff;
  overflow: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: 'Courier New', Consolas, monospace;
  font-size: 12px;
  line-height: 1.4;
  min-height: 100%;
  color: #333;
}
</style>
